import React, {PropsWithChildren, useEffect, useRef, useState} from 'react';
import st from './block-control.module.css'

interface PropsType {
   cls?: string | string[];
   focusCls?: string | string[];
   controlBar?: JSX.Element;
   canDrag?: boolean;
   onMouseEnter?: () => void;
   onMouseLeave?: () => void;
}

export const ClsControl: React.FC<PropsWithChildren<PropsType>> = ({
    cls = st['box-container'],
    focusCls = st['bcg-ccc'],
    children,
    controlBar,
    canDrag = false,
    onMouseEnter, onMouseLeave
}) => {

   const [focus, setFocus] = useState(false)
   const containerRef = useRef(null);

   function getEl() {
      const hostEl = containerRef.current as any as HTMLElement;
      return hostEl.children.item(0);
   }

   function handleNodeClass(type: 'add' | 'remove') {
      return (cls: string | string[]) => {
         const childNode = getEl();
         if (childNode) {
            if (Array.isArray(cls)) {
               childNode.classList[type](...cls)
               return;
            }
            childNode.classList[type](cls)
         }
      }
   }
   const addNodeClass = handleNodeClass('add')
   const removeNodeClass = handleNodeClass('remove')

   useEffect(() => {
      addNodeClass(cls)
   }, [])

   useEffect(() => {
     const childNode = getEl();
     if (childNode) {
        focus ? addNodeClass(focusCls) : removeNodeClass(focusCls)
     }
   }, [focus])

   function showControlBar() {
      if (!controlBar) return null;
      if (focus) {
         return controlBar;
      } else {
         return null;
      }
   }


   return <div
       ref={containerRef}
       onMouseEnter={() => { setFocus(true); onMouseEnter && onMouseEnter() }}
       onMouseLeave={() => { setFocus(false); onMouseLeave && onMouseLeave() }}
   >
      <div id='bcc' style={{padding: '4px 0 4px 12px'}}>
         {children}
         {showControlBar()}
      </div>
   </div>
}
